const {
  comMysql
} = require("../db/mysql")
const xss = require("xss")

const addChat = (req, res) => {
  let {
    username,
    content,
    to,
    userId
  } = req.query
  content = xss(content)
  console.log(content);
  
  let time = new Date().getTime()
  let sql = `insert into chat(username,message,time,toUser,userId) values(?,?,?,?,?)`
  let arr = [username, content, time, to, userId]
  
  return comMysql(sql, arr)
}

const delChat = (req, res) => {
  let {
    id,
  } = req.body
  let sql = `delete from chat where id = ?`
  let arr = [id]
  return comMysql(sql, arr)
}

const searchChat = (req, res) => {
  let {
    username,
    Tousername
  } = req.query
  let sql = `select chat.message,chat.time,chat.id,chat.toUser,users.avatar,users.realname,users.id as "UserId" from chat LEFT JOIN users on chat.username = users.username`
  if (username) {
    sql += ` where (chat.username = ? and chat.toUser = ?) or (chat.username = ? and chat.toUser = ?)`
  }
  let arr = [username, Tousername,Tousername,username]
  
  
  return comMysql(sql, arr)
}

const searchLastChat = (req,res)=>{
  let sql =  `SELECT chat.message,chat.time, users.avatar, users.realname, users.username FROM users LEFT JOIN chat ON chat.username = users.username WHERE chat.time IN ( select max(time) FROM chat GROUP BY username HAVING username <> "2628735401" )`
  return comMysql(sql)
}

module.exports = {
  addChat,
  delChat,
  searchChat,
  searchLastChat
}